# -*- coding: utf-8 -*-
import datetime, time
import os, random
from django.db import models
import django.utils.timezone as timezone
from django.utils.html import format_html
from django.core.files.storage import FileSystemStorage
from stdimage.models import StdImageField
from DjangoUeditor.models import UEditorField
from apps.map import *
from .storage import *


# Create your models here.


class Good(models.Model):
    '''
    商品
    title price_purchase price_sell
    '''
    def __init__(self, *args, **kwargs):
        super(Good, self).__init__(*args, **kwargs)  # 在先
        self.num = self.good_purchase_num() - self.good_sale_num()

    code = models.CharField(verbose_name='编码', max_length=100, blank=True, null=True, unique=True)
    title = models.CharField(verbose_name='商品标题', max_length=100, blank=False)
    price_purchase = models.IntegerField(verbose_name='进价', blank=False)
    price_sell = models.IntegerField(verbose_name='售价', blank=False)
    fk_store = models.ForeignKey(
        verbose_name='店铺',
        blank=True,
        null=True,
        to='organization.Store',
        # on_delete=models.CASCADE
    )
    size = models.CharField(verbose_name='尺码', choices=SIZE_CHOICES, max_length=5, default='fz')
    num = models.IntegerField(verbose_name='库存',default=0,blank=True,null=True)
    material = models.CharField(verbose_name='材料', max_length=200, blank=True, null=True)
    graphy = models.CharField(verbose_name='图案', max_length=200, blank=True, null=True)
    style = models.CharField(verbose_name='风格', max_length=200, blank=True, null=True)
    year = models.CharField(verbose_name='年份', max_length=4, choices=YEAR_LIST, blank=True, null=True)
    season = models.CharField(verbose_name='季节', max_length=30, choices=SEASON_LIST, blank=True, null=True)
    sleeve = models.CharField(verbose_name='袖型', max_length=30, blank=True, null=True)
    collar = models.CharField(verbose_name='领型', max_length=30, blank=True, null=True)
    length = models.CharField(verbose_name='版长', max_length=10, choices=CLOTHING_LENGTH, blank=True, null=True)
    tailer = models.CharField(verbose_name='缝纫工艺', max_length=30, blank=True, null=True)
    dye = models.CharField(verbose_name='染色工艺', max_length=30, blank=True, null=True)
    created = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
    modified = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    # created = models.DateTimeField(verbose_name='创建时间', default=timezone.now())
    # modified = models.DateTimeField(verbose_name='修改时间', default=timezone.now())
    info = UEditorField(
        verbose_name=u'备注/补充',
        blank=True,
        width=600, height=300,
        # toolbars="full",
        imagePath="good/good/",  # 相对路径
        filePath="good/good/",
        default=""  # 新增字段时，为避免出错可以设置default=""
        # upload_settings={"imageMaxSize":1204000},
        # settings={},
        # command=None,
        # event_handler=myEventHander(),
        # blank=True
    )

    class Meta:
        verbose_name = "商品"
        verbose_name_plural = verbose_name
        ordering = ["-created"]
        # db_table  # default app_model
        # unique_together = (("field", "field"),)

    def good_purchase_num(self):
        quantity = 0
        goodsinpurchase = self.good_goodinpurchase.filter(fk_good_id=self.id,created__lte=datetime.datetime.now())
        if goodsinpurchase.exists():
            for good in goodsinpurchase:
                quantity += good.quantity
        return quantity
    good_purchase_num.short_description = u'进货件数'

    # 消耗可以算作亏本出售
    def good_sale_num(self):
        quantity = 0
        goodsinsale = self.good_goodinsale.filter(fk_good_id=self.id,created__lte=datetime.datetime.now())
        if goodsinsale.exists():
            for good in goodsinsale:
                quantity += good.quantity
        return quantity
    good_sale_num.short_description = u'销售件数'

    def __str__(self):
        # return ' {0} : {1} '.format(self.type,self.title)
        return "{0}|{1}".format(self.code,self.title)

    def save(self, *args, **kwargs):
        if not self.code:
            now = datetime.datetime.now()  # datetime 时间元组
            str_date = now.strftime("%Y%m%d")
            # import time
            # time.strftime('%Y%m%d%H%M%S')
            str_random = str(now.timestamp())[-5:]
            self.code = str_date + str_random
        # self.modified = timezone.now()
        super(Good, self).save(*args, **kwargs)  # Call the "real" save() method.


from django.core.files.storage import FileSystemStorage
from django.http import HttpResponse


class GoodMultimediaStorage(FileSystemStorage):
    from django.conf import settings

    def __init__(self, location=settings.MEDIA_ROOT, base_url=settings.MEDIA_URL):
        # 初始化
        super(GoodMultimediaStorage, self).__init__(location, base_url)

    # 重写 _save方法
    def _save(self, name, content):
        return super(GoodMultimediaStorage, self)._save(name, content)


class GoodMultimedia(models.Model):
    '''
    商品描述资料
    '''
    fk_good = models.ForeignKey(
        verbose_name='商品',
        blank=False,
        to='good.Good',
        related_name='good_goodmultimedia'  # default 'goodmultimedia_set'
        # https: // blog.csdn.net / wuliangtianzu / article / details / 82656647
        # serializer能用到
        # good_instance.good_goodmultimedia.all()
        # on_delete=models.CASCADE
    )
    type = models.CharField(verbose_name='类型', max_length=30, choices=MULTIMEDIA, default='00')
    created = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
    modified = models.DateTimeField(verbose_name='修改时间', auto_now=True)

    uri = StdImageField(
        verbose_name='资源',
        upload_to='good/multimedia/',
        # storage=GoodMultimediaStorage(),
        variations={
            'large': (600, 400),
            'thumbnail': (100, 100, True),
            'medium': (300, 200),
        }
    )

    # uri = models.ImageField(
    #     verbose_name='资源',
    #     upload_to='good/multimedia/',
    #     storage=GoodMultimediaStorage(),  # 括号一定不要忘了
    # )
    # self.uri.name = new_name
    # self.uri.name  # good/multimedia/201902259098204.jpg
    # self.url.path  # /media/good/multimedia/201902259098204.jpg
    # self.url.url   # http://127.0.0.1:8000/media/good/multimedia/201902259098204.jpg

    def uri_image(self):
        # self.uri.url  good/multimedia/201902259098204.jpg
        # self.uri /media/good/multimedia/201902259098204.jpg
        # { % static 'media/org/2016/11/imooc.png' %}
        # 这里还是重点，注意调用方式，‘%’变成‘{}’了！
        return format_html(
            '<img src="{}" alt="图片未加载" width="100px"/>',
            self.uri.url,
            # self.uri.medium.url,
            # self.uri.large.url,
            # self.uri.thumbnail.url,
        )

    uri_image.short_description = u'图片'  # 显示的列名

    def fk_good_title(self):
        return self.fk_good.title

    fk_good_title.short_description = u'商品'

    class Meta:
        verbose_name = "商品描述"
        verbose_name_plural = verbose_name
        ordering = ["fk_good"]
        # db_table  # default app_model
        # unique_together = (("field", "field"),)

    def __str__(self):
        # return ' {0} : {1} '.format(self.type,self.title)
        return str(self.uri)

    def save(self, *args, **kwargs):
        return super(GoodMultimedia, self).save(*args, **kwargs)  # Call the "real" save() method.


